package com.drpclub.gamebackend.common.utils;

import cn.hutool.Hutool;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import com.drpclub.gamebackend.common.constant.ActionUri;
import com.drpclub.gamebackend.common.constant.RootUri;
import com.drpclub.gamebackend.exception.IgnoreException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import static com.drpclub.gamebackend.common.constant.Const.DOMAIN;
import static com.drpclub.gamebackend.common.constant.Const.LOCALHOST;
import static com.drpclub.gamebackend.common.utils.SpringContextUtils.isDev;

/**
 * @author ：drp
 * @date ：Created in 2020/5/23 11:15
 */
@Component
public class FileUtils {

    @Value("${filePath}")
    private String uploadPath;

    public static String fullFilePath(String headImage) {
        return (isDev() ? LOCALHOST : DOMAIN) + headImage;
    }

    public String getFileSaveRealPath(String path, boolean createDir) {
        path = path.startsWith ("/") ? path : "/" + path;
        path = uploadPath + path;
        if (createDir) {
            File dir = new File (path);
            if (!dir.exists ()) {
                if (!dir.mkdirs ()) throw new IgnoreException ("创建目录失败");
            }
        }
        return path;
    }

    public static void transMultipartFileTo(MultipartFile multipartFile,
                                            String filename,
                                            String filePath) throws IOException {
        final File file = new File (filePath);
        if (!file.exists ()) {
            if (!file.mkdirs ()) throw new IgnoreException ("创建目录失败");
        }

        filePath = filePath.endsWith ("/") ? filePath : filePath + "/";

        InputStream is = multipartFile.getInputStream ();
        Img.from(is)
                .setQuality(0.7)
                .write(FileUtil.file(filePath + filename));
    }

    public static String getHeaderImgPath(String filename, String username) {
        return String.format ("%s%s?filename=%s&username=%s",
                RootUri.FILE, ActionUri.GET_HEADER, filename, username);
    }

    public static String getCoverImgPath(String filename, String username) {
        return String.format ("%s%s?filename=%s&username=%s",
                RootUri.FILE, ActionUri.GET_COVER, filename, username);
    }


    public static String getContentImgPath(String filename, String contentId, String username) {
        return String.format ("%s%s?filename=%s&contentId=%s&username=%s",
                RootUri.FILE, ActionUri.GET_CONTENT, filename, contentId, username);
    }
}
